package com.siashan.toolkit.sms.aliyun;

import com.siashan.toolkit.sms.cache.SmsCacheAutoConfiguration;
import com.siashan.toolkit.sms.cache.SmsCacheTemplate;
import com.siashan.toolkit.sms.core.entity.SmsFrequencyLimitConfig;
import com.siashan.toolkit.sms.core.entity.SmsTemplate;
import com.siashan.toolkit.sms.core.entity.SmsWhiteList;
import com.siashan.toolkit.sms.core.utils.SmsTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.List;
import java.util.Map;

/**
 * 阿里云发送端点自动配置
 *
 * @author siashan
 * @since v1.0.1
 */
@Configuration
@EnableConfigurationProperties(AliyunSmsProperties.class)
@Import(SmsCacheAutoConfiguration.class)
public class AliyunSmsAutoConfiguration {


    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    @Autowired
    private SmsCacheTemplate smsCacheTemplate;

    /**
     * 构造阿里云发送处理
     *
     * @return 阿里云发送处理
     */
    @Bean
    @ConditionalOnMissingBean
    public AliyunSmsSendExecutor aliyunSmsSendExecutor() {
        List<SmsTemplate> templateList = aliyunSmsProperties.getTmpls();
        Map<String, SmsTemplate> templateMap = SmsTemplateUtils.transMap(templateList);
        AliyunSmsConfig config = aliyunSmsProperties.getConfig();
        SmsWhiteList whiteList = aliyunSmsProperties.getWhiteList();
        SmsFrequencyLimitConfig frequencyLimit = aliyunSmsProperties.getFrequencyLimit();
        AliyunSmsSendExecutor executor = new AliyunSmsSendExecutor(config,templateMap, whiteList,frequencyLimit);
        return executor;
    }

    /**
     * 构造阿里云发送模板类
     *
     * @return 阿里云发送模板类
     */
    @Bean
    @ConditionalOnMissingBean
    public AliyunSmsTemplate aliyunSmsTemplate() {
        AliyunSmsTemplate aliyunSmsTemplate = new AliyunSmsTemplate(smsCacheTemplate, aliyunSmsSendExecutor());
        return aliyunSmsTemplate;
    }

}
